package com.zhuoli.service.springboot.test.util.service.impl;

import com.zhuoli.service.springboot.test.util.common.HttpUtils;
import com.zhuoli.service.springboot.test.util.common.request.DoPostRequest;
import com.zhuoli.service.springboot.test.util.service.PostControllerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhuoli
 * @Date: 2018/9/6 13:44
 * @Description:
 */
@Service
@Slf4j
public class PostControllerServiceImpl implements PostControllerService {

    private ExecutorService threadPool = Executors.newCachedThreadPool();

    @Override
    public String postUrl(DoPostRequest doPostRequest) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id", doPostRequest.getId().toString()));

        try {
            for (int i = 0; i < doPostRequest.getThreadNum(); i++) {
                Runnable runnable = () -> {
                    try {
                        HttpUtils.postUrl(doPostRequest.getUrl(), params);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };

                for (int j = 0; j < doPostRequest.getPostNum(); j++) {
                    threadPool.execute(runnable);
                }
            }
            return "success";
        } catch (Exception e) {
            log.error("post url error {}", e.getMessage());
            return "fail";
        }
    }
}
